package com.xxmw.transaction.common.excep;

import com.xxmw.transaction.common.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Set;

@Slf4j
public abstract class GlobExceptionHandler {

	/**
	 * 验证类异常 controller层参数验证
	 * @param e
	 * @return
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	public R constraintViolationException (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
		String message = null;
		for(ConstraintViolation<?> constraintViolation : constraintViolations) {
			message = constraintViolation.getMessage();
			break;
		}
		log.error("【**********验证信息异常:{}**********】", message);
		return R.error(message);
	}

	/**
	 * 验证类异常 实体类里面属性验证
	 * @param e
	 * @return
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R methodArgumentNotValidException (MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		String message = null;
		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			message = fieldError.getDefaultMessage();
			break;
		}
		log.error("【**********验证信息异常:{}**********】", message);
		return R.error(message);

	}

//	@ExceptionHandler(DuplicateKeyException.class)
//	public R handleDuplicateKeyException(DuplicateKeyException e) {
////		log.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
//		log.error(e.getMessage(), e);
//		return R.error("策略重复");
//	}

	/**
	 * 缺少权限异常捕获
	 * @param e
	 * @return
	 */
	@ExceptionHandler(UnauthorizedException.class)
	public R UnauthorizedException (UnauthorizedException e) {
		log.error("权限异常",e);
		return R.error("无权限访问");
	}

	/**
	 * 系统异常
	 * @param e
	 * @return
	 */
    @ExceptionHandler(Exception.class)
    public R exception(Exception e){
    	//日志打印
		log.error("", e);
        return R.error("系统繁忙稍后重试");
    }
}
